<template>
  <div class="containerBox">
    <el-form ref="form" :model="dataForm" label-width="110px">
      <el-form-item label="商品名称">
        <el-input  v-model="dataForm.goodsName" placeholder="单行输入"></el-input>
      </el-form-item>
      <el-form-item label="商品分类">
        <div class="goodClass" v-for="(item, index) in dataForm.goodsClass" :key="index">
          <span>一级分类</span>
          <el-select v-model="item.firstClass">
            <el-option value="DOG" label="狗"></el-option>
            <el-option value="CUT" label="猫"></el-option>
          </el-select>
          <span>二级分类</span>
          <el-select v-model="item.secondClass">
            <el-option value="ZHULAING" label="主粮"></el-option>
            <el-option value="LINGSHI" label="零食"></el-option>
          </el-select>
          <span>三级分类</span>
          <el-select v-model="item.thirdClass">
            <el-option value="CNZHULAING" label="国产主粮" ></el-option>
            <el-option value="JKZHULAING" label="进口主粮" ></el-option>
          </el-select>
        </div>
        <el-button class="addClass" @click="addSomthing('addClass')">添加分类</el-button>
      </el-form-item>
      <el-form-item label="商品规格">
        <div class="specB" v-for="(item, index) in dataForm.specifications" :key="'01' + index">
          <el-form-item label="规格名称">
            <el-input :disabled="item.editOff" v-model="item.specName"></el-input>
          </el-form-item>
          <el-form-item label="规格值">
            <span class="specVal" v-for="(items, index) in item.specVal" :key="'03' + index">
            {{items}}
              <i class="delBtn hover" v-if="!item.editOff" @click="addSomthing('delVal',index, item.specVal)">-</i>
            </span>
            <p class="addBtn" v-if="!item.editOff">
              <el-input value="" v-model="specValue"></el-input>
              <el-button @click="addSomthing('addSpecVal', index)">添加</el-button>
            </p>
          </el-form-item>
          <p class="operations">
            <a class="editSpec" v-if="item.editOff" @click="addSomthing('editSpec',index, item)">编辑</a>
            <a class="sureAddSpec" v-if="!item.editOff" @click="addSomthing('sureAddSpec',index, item)">确定添加此规格</a>
            <a class="delSpec" v-if="dataForm.specifications.length > 1" @click="addSomthing('delSpec',index, item)">删除</a>
          </p>
        </div>
        <el-button class="addClass" @click="addSomthing('addSpec')">添加规格</el-button>
      </el-form-item>
      <el-form-item label="价格库存">
        <el-table
          ref="multipleTable"
          :data="dataForm.priceInventory"
          tooltip-effect="dark"
          style="width: 100%"
        >
          <el-table-column prop="goodsCode" label="价格（元）"></el-table-column>
          <el-table-column prop="goodsCode" label="划线价（元）"></el-table-column>
          <el-table-column prop="goodsCode" label="库存"></el-table-column>
          <el-table-column prop="goodsCode" label="商品条形码"></el-table-column>
          <el-table-column prop="goodsCode" label="规格图片"></el-table-column>
          <el-table-column prop="goodsCode" label="运费设置（元）"></el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="商品标签">
        <div class="tags">
          <span>标签组</span>
          <el-select v-model="chooseTagDate1.tagNameId" @change="changeId1" placeholder="请选择">
            <el-option
              v-for="item in goodTagDate1"
              :key="item.tagId"
              :label="item.tagName"
              :value="item.tagId">
            </el-option>
          </el-select>
          <span>标签内容</span>
          <el-select v-model="chooseTagDate2.tagValId" @change="changeId2" placeholder="请选择">
            <el-option
              v-for="item in goodTagDate2"
              :key="item.tagId"
              :label="item.tagName"
              :value="item.tagId">
            </el-option>
          </el-select>
          <el-button @click="addSomthing('addTag')">添加标签</el-button>
        </div>
        <span class="specVal" v-for="(item, index) in dataForm.goodsTags" :key="item.tagValId">
          {{item.tagVal}} <i class="delBtn" @click="addSomthing('delTagVal', index, item)">-</i>
        </span>
      </el-form-item>
      <el-form-item label="商品主图">
        <el-upload
          action="https://jsonplaceholder.typicode.com/posts/"
          multiple
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload1"
          :on-success="successUpload"
          :on-error="errorUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="商品详情">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload2">
          <div class="flex">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    name: 'goodsRelease',
    data () {
      return {
        // 主图
        dialogVisible: false,
        dialogImageUrl: '',
        // 详情图
        imageUrl: '',
        couldAddSpec: true,
        specValue: '',
        dataForm: {
          goodsName: '',
          goodsClass: [
            {
              firstClass: '',
              secondClass: '',
              thirdClass: ''
            }
          ],
          specifications: [
            {
              specName: '口味',
              specVal: ['羊肉', '鸡肉', '鸭肉'],
              editOff: true
            }, {
              specName: '重量',
              specVal: ['1kg', '2kg', '5kg'],
              editOff: true
            }
          ],
          priceInventory: null,
          goodsTags: [],
          goodsMainPictures: [],
          goodsDetailPicture: null
        },
        goodTagDate1: [
          {
            tagName: '国产主粮',
            tagId: 1
          }, {
            tagName: '国产猫粮',
            tagId: 2
          }
        ],
        goodTagDate2: [
          {
            tagName: '全犬',
            tagId: 10
          }, {
            tagName: '幼犬',
            tagId: 11
          }, {
            tagName: '成犬',
            tagId: 12
          }
        ],
        chooseTagDate1: {
          // 选取标签组id  获取标签内容
          tagName: '',
          tagNameId: null
        },
        chooseTagDate2: {
          tagVal: '',
          tagValId: null
        }
      }
    },
    mounted () {
      console.log(this.diguiArrData(this.dataForm.specifications))
    },
    methods: {
      addSomthing (type, index, item) {
        if (type === 'addClass') {
          // 添加分类
          let newClass = {
            firstClass: '',
            secondClass: '',
            thirdClass: ''
          }
          this.dataForm.goodsClass.push(newClass)
        } else if (type === 'addSpecVal') {
          // 添加规格值
          let newVal = this.specValue
          if (newVal === '') return false
          this.dataForm.specifications[index].specVal.push(newVal)
          this.specValue = ''
        } else if (type === 'addSpec') {
          // 添加规格
          if (!this.couldAddSpec) return false
          let newSpec = {
            specName: '',
            specVal: [],
            editOff: false
          }
          this.dataForm.specifications.push(newSpec)
          this.couldAddSpec = false
        } else if (type === 'sureAddSpec') {
          this.specValue = ''
          // 确定添加该规格
          if (item.specName === '' || item.specVal.length === 0) {
            this.couldAddSpec = false
            return false
          } else {
            item.editOff = true
            this.couldAddSpec = true
            this.diguiArrData(this.dataForm.specifications)
          }
        } else if (type === 'editSpec') {
          // 编辑规格
          this.couldAddSpec = false
          item.editOff = false
        } else if (type === 'delSpec') {
          // 删除规格
          this.dataForm.specifications.splice(index, 1)
        } else if (type === 'delVal') {
          // 删除规格值
          item.splice(index, 1)
        } else if (type === 'addTag') {
          // 添加标签
          if (this.chooseTagDate1.tagNameId !== null && this.chooseTagDate2.tagVal !== '') {
            let newTagDate = this.chooseTagDate2
            var _this = this
            if (_this.dataForm.goodsTags.length > 0) {
              var off = 0
              _this.dataForm.goodsTags.forEach((val) => {
                if (val.tagValId === newTagDate.tagValId) {
                  off++
                }
              })
              if (off > 0) {
                return false
              } else {
                _this.dataForm.goodsTags.push(newTagDate)
              }
            } else {
              _this.dataForm.goodsTags.push(newTagDate)
            }
            _this.chooseTagDate2 = {
              tagVal: '',
              tagValId: null
            }
          } else {
            return false
          }
        } else if (type === 'delTagVal') {
          this.dataForm.goodsTags.splice(index, 1)
        }
      },
      changeId1 (val) {
        this.chooseTagDate1.tagNameId = val
      },
      changeId2 (callBackVal) {
        let _this = this
        this.goodTagDate2.forEach((val) => {
          if (val.tagId === callBackVal) {
            _this.chooseTagDate2.tagVal = val.tagName
          }
        })
      },
      diguiArrData (arr) {
        console.log(arr)
        if (arr.length <= 1) return arr
        let arr1 = arr[0].specVal
        let arr2 = arr[1].specVal
        let index = 1
        return assembleData(arr, arr1, arr2, index)
        function assembleData (arr, arr1, arr2, index) {
          // 空数组
          if (!arr1.length) arr1 = ['']
          // 空数组
          if (!arr2.length) arr2 = ['']
          let arr3 = []

          for (let i = 0; i < arr1.length; i++) {
            for (let j = 0; j < arr2.length; j++) {
              if (arr1[i].length > 1) {
                // 如果数组里面多于两个数据，合并两个数组
                arr3.push([arr1[i], arr2[j]])
              } else {
                arr3.push([arr1[i], arr2[j]])
              }
            }
          }
          // console.log(arr3)
          // this.dataForm.priceInventory = arr3
          if (arr[index + 1]) {
            // 传入的数据下一项，不为空，再执行一次
            return assembleData(arr, arr3, arr[index + 1], index + 1)
          } else {
            return arr3
          }
        }
      },
      // 主图
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      beforeAvatarUpload1 (file) {
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG && !isPNG) {
          this.$message.error('上传主图只能是 JPG 和 PNG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传主图单张图片大小不能超过 2MB!请压缩')
        }
        return (isJPG || isPNG) && isLt2M
      },
      successUpload (response, file, fileList) {
        var newPicS = {
          url: file.url,
          id: response.id
        }
        this.dataForm.goodsMainPictures.push(newPicS)
      },
      errorUpload (err) {
        alert(err)
      },
      // 详情
      handleAvatarSuccess (res, file) {
        console.log(file)
        this.imageUrl = URL.createObjectURL(file.raw)
        let newPic = {
          id: file.response,
          url: this.imageUrl
        }
        this.dataForm.goodsDetailPicture = newPic
      },
      beforeAvatarUpload2 (file) {
        const isJPG = file.type === 'image/jpeg'
        const isPNG = file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 5

        if (!isJPG && !isPNG) {
          this.$message.error('上传详情图片只能是 JPG 和 PNG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传详情图片大小不能超过 5MB!')
        }
        return (isJPG || isPNG) && isLt2M
      }
    }
  }
</script>

<style scoped lang="less">
  .containerBox{
    .goodClass{
      display: inline-block;
      margin-bottom: 15px;
    }
    span{
      font-size:14px;
      color:#606266;
    }
    .goodClass:last-child{
      margin:0;
    }
    .goodClass /deep/ .el-select{
      margin-right:15px;
    }
    .goodClass /deep/ .el-select .el-input__inner{
      width:150px;
    }
    /deep/ .el-input--medium > .el-input__inner {
      width:200px;
    }
    /deep/ .el-button{
      color:#fff;
      background: #008fff;
      padding:10px;
    }

    .specB {
      /*width:800px;*/
      border: 1px solid #e5e5e5;
      -webkit-border-radius: 10px;
      -moz-border-radius: 10px;
      border-radius: 10px;
      padding:15px;
      margin-bottom: 15px;
      position: relative;
      /deep/ .el-form-item{
        margin-bottom: 10px;
      }
      .addBtn{
        display: inline-block;
        position: relative;
        /deep/ .el-input--medium  .el-input__inner{
          width:80px !important;
        }
        /deep/ .el-button{
          position: absolute;
          top:0;
          left:77px;
        }
      }
      .operations{
        position: absolute;
        top:10px;
        right:10px;
        a{
          margin-right:10px;
        }
      }
      .delSpec{
        color: #e95d6b;
      }

    }
    .specB:last-child{
      margin-bottom: 0;
    }

    .tags .el-select{
      margin-right:15px;
      margin-bottom: 15px;
      width:150px;
      /deep/ .el-input__inner{
        width:150px;
      }
    }
    span.specVal{
      line-height:34px;
      padding:0 10px;
      margin-right:10px;
      border:1px solid #e5e5e5;
      background: #fff;
      -webkit-border-radius: 5px;
      -moz-border-radius: 5px;
      border-radius: 5px;
      position: relative;
      .delBtn{
        position: absolute;
        width:15px;
        line-height:12px;
        -webkit-border-radius: 15px;
        -moz-border-radius: 15px;
        border-radius: 15px;
        background: orangered;
        color: #fff;
        text-align: center;
        height:15px;
        top:-5px;
        right:-5px;
      }
    }

    /deep/ .avatar-uploader {
      .el-upload {
        background: #fff;
        width: 200px;
        height:200px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }
      .flex{
        width:100%;
        height:100%;
      }
      .avatar {
        max-width: 100%;
        max-height: 100%;
        display: block;
      }
    }

  }
</style>
